'use strict';

const Service = require('egg').Service;

class UserService extends Service {
  async add({ roleId, username, realName }) {
    const { ctx } = this;
    try {
      const res = await ctx.model.User.create({
        username,
        roleId,
        realName,
        password: '123456',
        createdTime: Date.now(),
      });
      await ctx.model.RoleUser.create({
        userId: res.id,
        roleId,
      });
      return this.ctx.helper.success({ id: res.id }, '新增成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async find(id) {
    const { ctx } = this;
    try {
      const res1 = await ctx.model.User.findAll({
        attributes: [ 'id', 'username', 'realName' ],
        where: { id, logicDelete: 0 },
        raw: true,
      });
      const res2 = await ctx.model.RoleUser.findAll({
        attributes: [ 'id', 'userId', 'roleId' ],
        where: { userId: id },
        raw: true,
      });
      res1[0].roleId = res2[0].roleId;
      return this.ctx.helper.success(res1[0], '更新成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async update({ username, realName, roleId, id }) {
    const { ctx } = this;
    try {
      const res = await ctx.model.User.update(
        { username, realName, roleId, updatedTime: Date.now() },
        { where: { id } }
      );
      await ctx.model.RoleUser.update(
        { roleId },
        { where: { userId: id } }
      );
      return this.ctx.helper.success(res[0]);
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async delete(id) {
    const { ctx } = this;
    try {
      const res = await ctx.model.User.update(
        { logicDelete: 1 },
        { where: { id } }
      );
      return this.ctx.helper.success(res[0], '删除成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async list(current = 1, pageSize = 10) {
    const { ctx } = this;
    try {
      const res = await ctx.model.User.findAndCountAll({
        where: { logicDelete: 0 },
        order: [[ 'id', 'DESC' ]],
        offset: (current - 1) * pageSize, // 查询的起始下标
        limit: pageSize, // 查询的条数
      });
      return this.ctx.helper.success(res);
    } catch (e) {
      return this.ctx.helper.fail(e);
    }
  }
}

module.exports = UserService;
